import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Spin, Checkbox } from 'antd';
import { CheckOutlined } from '@ant-design/icons';
import { mainStore } from '../stores';
import { myAxios } from '../axios';
import tools from '../utils/tools';
import './Login.less';

const Login = () => {
  const navigate = useNavigate();
  
  // 状态管理
  const [memory, setMemory] = useState(localStorage.getItem('memory') === 'true');
  const [form, setForm] = useState({
    name: '',
    pwd: ''
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

  // 组件挂载时检查是否有保存的账户信息
  useEffect(() => {
    if (memory) {
      const userSecret = JSON.parse(localStorage.getItem('userSecret') || '{}');
      if (userSecret.name) {
        setForm({
          name: userSecret.name,
          pwd: userSecret.pwd || ''
        });
      }
    }
  }, []);

  // 记住账户功能
  const keepAccount = () => {
    const newMemory = !memory;
    setMemory(newMemory);
    localStorage.setItem('memory', newMemory);

    // 如果选择记住账户，则保存当前输入的账户和密码
    if (newMemory && form.name) {
      const userSecret = {
        name: form.name,
        pwd: form.pwd,
      };
      localStorage.setItem('userSecret', JSON.stringify(userSecret));
    } else {
      // 如果取消记住账户，则清除保存的账户信息
      localStorage.removeItem('userSecret');
    }
  };

  // 页面跳转函数
  const toReg = () => {
    navigate('/reg');
  };

  // 表单输入处理
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setForm({
      ...form,
      [name]: value
    });
  };

  // 登录函数
  const login = async () => {
    // 防止重复提交
    if (isSubmitting) {
      return;
    }

    // 表单验证
    if (!form.name || !form.pwd) {
      tools.alertMsg('请输入用户名和密码', 'warning');
      return;
    }

    setIsSubmitting(true);
    
    try {
      // 发送登录请求
      const response = await myAxios.get('/login', {
        params: {
          name: form.name,
          pwd: form.pwd
        }
      });
      console.log(response)
      // 处理响应
      if (response.data && response.data.code === 200) {
        const { jwttoken, user } = response.data.data;
        
        // 保存token和用户信息
        localStorage.setItem('token', jwttoken);
        mainStore.saveUserData(user);
        
        // 如果选择了记住账户，更新保存的账户信息
        if (memory) {
          const userSecret = {
            name: form.name,
            pwd: form.pwd,
          };
          localStorage.setItem('userSecret', JSON.stringify(userSecret));
        }
        
        tools.alertMsg('登录成功', 'success');
        navigate('/home');
      } else {
        tools.alertMsg(response.data?.message || '登录失败，请检查用户名和密码', 'error');
      }
    } catch (error) {
      console.error('登录请求错误:', error);
      tools.alertMsg(error.response?.data?.message || '登录失败，请稍后重试', 'error');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="login-container">
      <div className="post"></div>
      <div className="log-shell">
        {/* 中部内容区域 */}
        <div className="middle">
          {/* 顶部导航区域 */}
          <div className="nav-tabs">
            <div className="tab active">登录</div>
            <div className="tab" onClick={toReg}>注册</div>
          </div>
          {/* 登录表单 */}
          <div className="login-form">
            <div className="inp">
              <span className="label">用户名</span>
              <input 
                name="name"
                value={form.name}
                onChange={handleInputChange}
                spellCheck="false" 
                type="text" 
              />
            </div>
            <div className="inp">
              <span className="label">密码</span>
              <input
                name="pwd"
                value={form.pwd}
                onChange={handleInputChange}
                type="password"
                onKeyPress={(e) => e.key === 'Enter' && login()}
              />
            </div>
            <div className="memory" onClick={keepAccount}>
              <CheckOutlined className={`sel-icon ${!memory ? 'white' : ''}`} />
              <span>记住我</span>
            </div>
            <div className="bnt">
              <button onClick={login} disabled={isSubmitting}>
                {isSubmitting ? "登录中..." : "登录"}
              </button>
            </div>
          </div>
        </div>
      </div>
      {isSubmitting && <Spin tip="登录中..." fullscreen />}
    </div>
  );
};

export default Login;